package utile

import (
	"etcd/logger"
	"github.com/mojocn/base64Captcha"
	"image/color"
)

//configJsonBody json request body.
type configJsonBody struct {
	Id            string
	CaptchaType   string
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio
	DriverString  *base64Captcha.DriverString
	DriverChinese *base64Captcha.DriverChinese
	DriverMath    *base64Captcha.DriverMath
	DriverDigit   *base64Captcha.DriverDigit
}

type storeByRedis struct{}

func (s *storeByRedis) Set(id string, value string) {
	rds, _ := GetRedigo()
	err := rds.SetEx(id, value, 600)
	if err != nil {
		logger.Errorf("redis存储验证码失败，err：%s", err.Error())
	}
}

func (s *storeByRedis) Get(id string, clear bool) string {
	rds, _ := GetRedigo()
	value, err := rds.Get(id)
	if err != nil {
		logger.Errorf("redis获取验证码失败，err：%s", err.Error())
		return ""
	}
	return value
}

func (s *storeByRedis) Verify(id, answer string, clear bool) bool {
	value := s.Get(id, clear)
	if len(value) < 0 || value != answer {
		return false
	}
	if clear {
		rds, _ := GetRedigo()
		rds.Del(id)
	}
	return true
}

//var store = base64Captcha.DefaultMemStore
var store = &storeByRedis{}

func CreatCaptcha(captchaType string) (id string, b64s string, err error) {

	var param configJsonBody
	var driver base64Captcha.Driver

	switch captchaType {
	case "audio":
		driver = param.DriverAudio
	case "string":
		driver = param.DriverString.ConvertFonts()
	case "math":
		fonts := []string{}
		//font = append(font, "3Dumb.ttf")
		//font = append(font, "actionj.ttf")
		fonts = append(fonts, "ApothecaryFont.ttf")
		//font = append(font, "chromohv.ttf")
		//font = append(font, "Comismsh.ttf")
		//font = append(font, "DeborahFancyDress.ttf")
		var bgc *color.RGBA
		driver = base64Captcha.NewDriverMath(32, 107, 0, 0, bgc, fonts)
		//driver = param.DriverMath.ConvertFonts()
	case "chinese":
		driver = param.DriverChinese.ConvertFonts()
	default:
		driver = param.DriverDigit
	}

	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, err = c.Generate()
	return id, b64s, err
}

func VerifyCaptcha(id, VerifyValue string) bool {
	if !store.Verify(id, VerifyValue, true) {
		return false
	}
	return true
}
